﻿#include "widget5.h"
#include "ui_widget5.h"
#include <QAxObject>
#include <QDebug>
#include "poppler/poppler-qt5.h"
#include <QFileDialog>
#include <QLabel>
#include <QMessageBox>
#include <QPainter>
#include <QStyleOption>

Widget5::Widget5(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget5)
{
    ui->setupUi(this);
    setAutoFillBackground(true);
}

Widget5::~Widget5()
{
    delete ui;
}

void Widget5::clearWidget()
{
    clearLayout(ui->horizontalLayout);
}

void Widget5::loadWord()
{
    QApplication::processEvents();
    QString filename = QStringLiteral("%1/template/处分文件temp.pdf").arg(QApplication::applicationDirPath());
    Poppler::Document* document = Poppler::Document::load(filename);//加载pdf文件
    if (!document || document->isLocked())
    {
        QMessageBox::information(this,"提示",QString::fromUtf8("无法打开文件:%1").arg(filename));//如果加载不成功，输出错误信息，并返回
        delete document;
        return;
    }
    //再次检查document是否可用
    if (document == 0) {
    // ui->label_message->setText(QString::fromUtf8("文件内无内容:%1").arg(filename));//不可用则输出错误信息，并返回
    return;
    }
    //将PDF文档的每一页输出为QImage
    for(int pageNumber=0;pageNumber < document->numPages();pageNumber++)
    {
        //获取指定页码的页面，页码从0开始
    Poppler::Page* pdfPage = document->page(pageNumber);
    if (pdfPage == 0)
    {
            return;
    }
        //将页面内容转换为QImage
    QImage image = pdfPage->renderToImage();
    // double xres=72.0, yres=72.0; int x=-1, y=-1, width=-1, height=-1;
    // QImage image = pdfPage->renderToImage(xres, yres, x, y, width, height);
    // if (image.isNull()) {
    // qDebug()
    // return;
    // }
    // 在QLabel中显示QImage
    QLabel *label = new QLabel(this);
    label->setPixmap(QPixmap::fromImage(image));
    ui->horizontalLayout->addWidget(label);
    //使用完后记得释放掉Poppler::Page* pdfPage
    delete pdfPage;
    }
    delete document;
}

void Widget5::on_pushButton_clicked()
{
    emit SignalWidget5Print();
}

void Widget5::clearLayout(QLayout *layout)
{
    QLayoutItem* item = nullptr;
    while ((item = layout->takeAt(0)))
    {
        if(item->layout())
        {
            clearLayout(item->layout());
        }
        if(item->widget())
        {
            delete item->widget();
        }
        delete item;
    }
}

void Widget5::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap pixmap(":/res/bg.jpg");
    painter.drawPixmap(this->rect(),pixmap);
}

void Widget5::on_pushButton_2_clicked()
{
    emit SignalWidget5Back();
}
